package com.example.demo.dynamic_datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 17:31 2018/7/7
 */
@Configuration
@MapperScan(basePackages = {"com.example.*.dao"},sqlSessionFactoryRef = "sqlSessionFactory")
public class SqlSessionConfig {
     @Autowired
     @Qualifier("myRoutingDataSource")
     private DataSource myRoutingDataSource;

      @Bean(name = "sqlSessionFactory")
     public SqlSessionFactory sqlSessionFactory() throws Exception {
          SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
          factoryBean.setDataSource(myRoutingDataSource);
          return factoryBean.getObject();
      }
      @Bean(name = "sqlSessionTemplate")
      public SqlSessionTemplate orderSqlSessionTemplate() throws Exception {
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactory());
        return sqlSessionTemplate;
      }
    @Bean
    public PlatformTransactionManager platformTransactionManager() {
        return new DataSourceTransactionManager(myRoutingDataSource);
    }
}
